package com.db.admin

import grails.converters.JSON

import java.awt.image.BufferedImage

import javax.imageio.ImageIO

import org.imgscalr.Scalr
import org.springframework.http.HttpStatus
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.multipart.MultipartHttpServletRequest

import com.db.gallery.Project
import com.db.gallery.ProjectGroup
import com.db.gallery.ProjectImage
import com.dg.properties.PropertyUtility

class AdminController {
	
	def grailsApplication

    def administrationOptions() {
		session.editEnabled = true
	}
	
	def disableEdit() {
		session.editEnabled = false
		redirect(controller: 'home', action: 'home')
	}
	
	def newProject() {
		def dataMap = [:]
		def projectGroups = ProjectGroup.findAll()
		dataMap.put("projectGroups", projectGroups)
		
		return dataMap
	}
	
	def editProject() {
		redirect(controller: "gallery", action: "gallery", params: [editMode: 'true'])
	}
	
	def updateProject() {
		def projectName = params.projectName
		def projectDescription = params.projectDescription
		def projectIdString = params.projectId
		def projectId = Long.valueOf(projectIdString)
		def project = Project.findWhere(id : projectId)
		
		project.setName(projectName)
		project.setDescription(projectDescription)
		project.save()
	}
	
	def createNewProject() {
		def bla = params
		
		String projectImagesPath
		def projectName = params.projectName
		def projectDescription = params.projectDescription
		def projectGroupIdString = params.projectGroups
		def projectGroupId = Long.valueOf(projectGroupIdString)
		def projectGroup = ProjectGroup.findWhere(id : projectGroupId)
		
		Project newProject = new Project(projectName, projectDescription, projectGroup)
		newProject.save()
		
		projectImagesPath = PropertyUtility.getProjectImagePath(newProject.projectGroup.name, newProject.name)
		
		File projectImagesFolder = new File(projectImagesPath)
		
		if (projectImagesFolder.mkdirs()) {
			// TODO good
		} else {
			// TODO bad, delete project
		}
		
		redirect(action: "projectEditor", params: [projectId: newProject.id])
	}
	
	def projectEditor() {
		def dataMap = [:]
		
		String projectIdString = params.projectId
		Long projectId = Long.valueOf(projectIdString)
		
		Project project = Project.findWhere(id: projectId)
		
		dataMap.put("projectId", project.id)
		dataMap.put("projectName", project.name)
		dataMap.put("projectDescription", project.description)
		
		return dataMap
	}	
	
	// Example code below
	def upload() {
		String projectIdString = params.projectId
		Long projectId = Long.valueOf(projectIdString)
		
		Project project = Project.findWhere(id : projectId)		
		
		switch(request.method){
			case "GET":
				def results = []
				
				project.images.each { ProjectImage projectImage ->
					results << [
							name: projectImage.name,
							url: createLink(controller:'gallery', action:'getImageById', id: projectImage.id),
							thumbnail_url: createLink(controller:'gallery', action:'getUploaderThumbnail', id: projectImage.id),
							delete_url: createLink(controller:'admin', action:'deleteImage', id: projectImage.id),
							delete_type: "DELETE"
					]
				}
				render results as JSON
				break;
			case "POST":
				def results = []
				
				String imagePath
				
				imagePath = PropertyUtility.getProjectImagePath(project.projectGroup.name, project.name)
				imagePath += "/"
				
				if (request instanceof MultipartHttpServletRequest){
					for(filename in request.getFileNames()){
						MultipartFile file = request.getFile(filename)

						String fullFileName = file.originalFilename
						int lastIndex = fullFileName.lastIndexOf(".")
						String fileName = fullFileName.substring(0, lastIndex)
						String originalFileExtension = fullFileName.substring(lastIndex + 1)
						//String storageDirectory = grailsApplication.config.file.upload.directory?:'/tmp'

						File newFile = new File(imagePath + fullFileName)
						file.transferTo(newFile)

						BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 200);
						String thumbnailFileName = fileName + '-thumbnail.' + originalFileExtension
						File thumbnailFile = new File(imagePath + thumbnailFileName)
						ImageIO.write(thumbnail, originalFileExtension, thumbnailFile)

						ProjectImage projectImage = new ProjectImage(project, fullFileName, imagePath + fullFileName, imagePath + thumbnailFileName);
						if(projectImage.save()) {
							results << [
								name: projectImage.name,
								url: createLink(controller:'gallery', action:'getImageById', id: projectImage.id),
								thumbnail_url: createLink(controller:'gallery', action:'getUploaderThumbnail', id: projectImage.id),
								delete_url: createLink(controller:'admin', action:'deleteImage', id: projectImage.id),
								delete_type: "DELETE"
							]
						} else {
							// Error on save, probably a duplicate name
							String errorMessages = "Please verify that the picture name is unique for this project."
							
							results << [
								name: projectImage.name,
								error: errorMessages
							]
						}
					}
				}

				render results as JSON
				break;
			default: render status: HttpStatus.METHOD_NOT_ALLOWED.value()
		}
	}
	
	def deleteProject() {
		String projectIdString = params.projectId
		Long projectId = Long.valueOf(projectIdString)
		
		Project project = Project.findWhere(id: projectId)
		project.delete();
		
		String projectPath
		projectPath = PropertyUtility.getProjectPath(project.projectGroup.name, project.name)
		
		File projectFolder = new File(projectPath)
		projectFolder.delete()
		
		redirect(controller: "admin", action: "administrationOptions")
	}
	
	def deleteImage() {
		String imageIdString = params.id
		Long imageId = Long.valueOf(imageIdString)
		ProjectImage projectImage = ProjectImage.findWhere(id: imageId)
		
		File picFile = new File(projectImage.imagePath)
		picFile.delete()
		
		File thumbnailFile = new File(projectImage.thumbnailPath)
		thumbnailFile.delete()
		
		projectImage.delete()
		
		def result = [success: true]
		render result as JSON
	}
}
